const {
    createRecord,
    updateRecord,
    removeRecord,
    restoreRecord,
    findRecord,
    findRecordInfo,
} = require('../service/record.service')

const {sucOperation} = require("../constant/success.type");
const {failOperation} = require("../constant/err.type");

class RecordController {
    async create(ctx, next) {
        try {
            const { createdAt, updatedAt, ...res } = await createRecord(
                ctx.request.body
            );
            ctx.body = {
                ...sucOperation,
                result: res,
            };
        } catch (err) {
            return ctx.body = {
                ...failOperation
            };
        }
    }

    async update(ctx) {
        try {
            const res = await updateRecord(ctx.params.id, ctx.request.body);
            console.log(res)
            if (res) {
                ctx.body = {
                    ...sucOperation,
                    result: res,
                };
            } else {
                return ctx.body = {
                    ...failOperation
                };
            }
        } catch (err) {
            console.error(err);
        }
    }

    async remove(ctx) {
        const res = await removeRecord(ctx.params.id);

        if (res) {
            ctx.body = {
                ...sucOperation,
            };
        } else {
            return ctx.body = {
                ...failOperation
            };
        }
    }

    async restore(ctx) {
        const res = await restoreGoods(ctx.params.id);
        if (res) {
            ctx.body = {
                ...sucOperation,
            };
        } else {
            return ctx.body = {
                ...failOperation
            };
        }
    }

    async findAll(ctx) {
        // 1. 解析pageNum和pageSize
        const {
            pageNum = 1,
            pageSize = 10,
            ...params
        } = ctx.request.body;
        // 2. 调用数据处理的相关方法
        const res = await findRecord({ pageNum, pageSize,...params });
        // 3. 返回结果
        ctx.body = {
            ...sucOperation,
            result: res,
        };
    }

    async findOne(ctx) {
        const { id } = ctx.params;
        const result = await findRecordInfo(id);
        if (result) {
            ctx.body = {
                ...sucOperation,
                result,
            };
        } else {
            ctx.body = {
                code: 500,
                message: "id有误",
            };
        }
    }
}

module.exports = new RecordController()
